package com.huiztech.kaoqinji;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.huiztech.common.http.HuizBaseJsonResponseHandler.Callback;
import com.huiztech.kaoqinji.ClientDetailActivity.MyLocationListenner;
import com.huiztech.kaoqinji.VisitActivity.VisitAdapter;
import com.huiztech.kaoqinji.model.ClientData;
import com.huiztech.kaoqinji.model.ClientDetail;
import com.huiztech.kaoqinji.mvc.KaoqinBaseActivity;
import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

public class NearVisitActivity extends KaoqinBaseActivity implements OnClickListener {

    private ListView listView;
    private EditText searchEdit;
    private List<ClientDetail> list;
    private List<String> arrayList;
    private LinearLayout backLayout;
    private LinearLayout addLayout;
    private LinearLayout nearLayout;
    private VisitAdapter adapter;
    private ArrayAdapter<String> arrayAdapter;
    private String[] searchStr;

    public LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_near_visit);

        findView();

        searchEdit.addTextChangedListener(new watcher());

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(NearVisitActivity.this, ClientDetailActivity.class);
                intent.putExtra("customerPosition", position);
                startActivity(intent);
            }
        });

        list = new ArrayList<ClientDetail>();
        arrayList = new ArrayList<String>();
        arrayAdapter = new ArrayAdapter<String>(NearVisitActivity.this, R.layout.search_item, arrayList);
        controller.getCustomerData(AppConst.GET_DATA_FOR_NEARBY, 0, 0, new Callback<ClientData>() {
            @Override
            public void execute(ClientData obj) {
                list.clear();
                list = obj.getData();
                adapter = new VisitAdapter(NearVisitActivity.this, list);
                listView.setAdapter(adapter);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.visit_footprint_back_layout:
            finish();
            break;
        case R.id.visit_footprint_new_layout:
            startActivity(new Intent(NearVisitActivity.this, AddClientActivity.class));
            break;
        default:
            break;
        }
    }

    private void findView() {
        listView = (ListView) findViewById(R.id.list);
        searchEdit = (EditText) findViewById(R.id.visit_search_edit);
        backLayout = (LinearLayout) findViewById(R.id.visit_footprint_back_layout);
            backLayout.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    /**
     * EditText 监听输入框
     *
     * @author yuanlong
     *
     */
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setAddrType("all");
        option.setServiceName("com.baidu.location.service_v2.9");
        mLocClient.setLocOption(option);
    }

    /**
     * 手动触发一次定位请求
     */
    public void requestLocClick() {
        mLocClient.start();
        mLocClient.requestLocation();
    }

    /**
     * 定位监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) return;
            controller.getCustomerData(AppConst.GET_DATA_FOR_NEARBY, location.getLatitude(), location.getLongitude(), new Callback<ClientData>() {

                @Override
                public void execute(ClientData obj) {
                    list.clear();
                    list = obj.getData();
                    adapter = new VisitAdapter(NearVisitActivity.this, list);
                    listView.setAdapter(adapter);
                }});
        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }

    }

    class watcher implements TextWatcher {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s);
        }
    }

    /**
     * 客户列表适配器
     *
     * @author yuanlong
     *
     */
    public class VisitAdapter extends BaseAdapter implements Filterable {

        private List<ClientDetail> clientDetailList;
        Context context;
        private LayoutInflater inflater;
        protected ImageLoader imageLoader = ImageLoader.getInstance();
        DisplayImageOptions options;
        private ClientDetailFilter filter;

        public final class ViewHolder {
            ImageView imageView;
            TextView nameText;
            TextView companyText;
            TextView addressText;
        }

        public VisitAdapter(Context context, List<ClientDetail> clientDetailList) {
            this.clientDetailList = clientDetailList;
            this.context = context;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            imageLoader.init(ImageLoaderConfiguration.createDefault(context));
            options = new DisplayImageOptions.Builder().showStubImage(R.drawable.moren)
                    .showImageForEmptyUri(R.drawable.moren).showImageOnFail(R.drawable.moren).cacheInMemory()
                    .cacheOnDisc().imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                    .bitmapConfig(Bitmap.Config.RGB_565).build();
        }

        @Override
        public int getCount() {
            return clientDetailList.size();
        }

        @Override
        public Object getItem(int position) {
            return clientDetailList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ClientDetail c = clientDetailList.get(position);
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.visit_list_item, null);
                holder.nameText = (TextView) convertView.findViewById(R.id.visit_item_name);
                holder.companyText = (TextView) convertView.findViewById(R.id.visit_item_company);
                holder.imageView = (ImageView) convertView.findViewById(R.id.visit_item_image);
                holder.addressText = (TextView) convertView.findViewById(R.id.visit_item_address);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (c.getName() != null) {
                holder.nameText.setText(c.getName());
            }
            if (c.getCompanyName() != null) {
                holder.companyText.setText(c.getCompanyName());
            }
            if (c.getCompanyAddress() != null) {
                holder.addressText.setText(c.getCompanyAddress());
            }
            if (c.getImage().equals("")) {
                holder.imageView.setBackgroundResource(R.drawable.moren);
            } else {
                imageLoader.displayImage(AppConst.KAOQIN_UPLOAD_URL + c.getImage(), holder.imageView, options);
            }
            return convertView;
        }

        @Override
        public Filter getFilter() {
            if (filter == null) {
                filter = new ClientDetailFilter(clientDetailList);
            }
            return filter;
        }

        private class ClientDetailFilter extends Filter {
            private List<ClientDetail> original;

            public ClientDetailFilter(List<ClientDetail> clientDetail) {
                this.original = clientDetail;
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint == null || constraint.length() == 0) {
                    results.values = original;
                    results.count = original.size();
                } else {
                    List<ClientDetail> mList = new ArrayList<ClientDetail>();
                    for (ClientDetail c : original) {
                        if (c.getName().toUpperCase().startsWith(constraint.toString().toUpperCase())) {
                            mList.add(c);
                        }
                    }
                    results.values = mList;
                    results.count = mList.size();
                }
                return results;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                clientDetailList = (List<ClientDetail>) results.values;
                model.put("clientDetail", clientDetailList);
                notifyDataSetChanged();
            }

        }

    }
}
